package com.example.demo.Aspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.example.demo.GeneralResponse.APIResponse;
import com.example.demo.Service.HRService;
import com.example.demo.Service.TokenService;

@Component
@Aspect
@Order(1)
public class SpecialPass {

	
	@Autowired
	private TokenService tokenService;
	@Autowired
	private HRService hrService;
	
	@Pointcut("execution(public * com.example.demo.Controller.QueryController.queryExpByexpid(..))")
	public void authorityassure() {
	}
	
	/**
	* @author:  郑皓杰 吴嘉鑫
	* @methodsName: authorityAssure
	* @description: 在进行exp查询时验证hr权限
	* @param:  ProceedingJoinPoint proceedingjoinpoint
	* @return: Object
	* @throws: 
	*/
	@Around("authorityassure()")
	public Object authorityAssure(ProceedingJoinPoint proceedingjoinpoint)throws Throwable{
		Object[] args = proceedingjoinpoint.getArgs();
		HttpServletRequest request = (HttpServletRequest) args[0];
		HttpServletResponse response = (HttpServletResponse) args[1];
		String nowtoken = request.getHeader("Token");
		response.setHeader("Access-Control-Expose-Headers","State,Token");
		if(nowtoken == null) {
			response.setHeader("State","UNAUTHORIZEDACCESS");
			return APIResponse.fail("Invalid Token");//查不到token说明第一次登录
		}
				Integer companyID = tokenService.getCompanyIDfromToken(nowtoken);
				Integer desid=Integer.parseInt(request.getParameter("desid"));

		String result = hrService.queryAuthority(companyID, desid);
		if(result.equals("accessthrough")) {
			response.setHeader("State","ALLOWED");
			return proceedingjoinpoint.proceed(args);
		}
		else {
			response.setHeader("State","UNABLEVISIT");
			return APIResponse.fail("Invalid Token");
		}
	}
}
